package com.lmx.wuzhangshao.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import cn.bmob.v3.BmobSMS
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.QueryListener
import cn.bmob.v3.listener.UpdateListener
import com.lmx.wuzhangshao.MyApplication
import com.lmx.wuzhangshao.R
import com.lmx.wuzhangshao.util.SharedPreUtil
import com.lmx.wuzhangshao.util.SimpleUtil
import com.lmx.wuzhangshao.util.ToastUtil
import kotlinx.android.synthetic.main.activity_login.*

/**
 * @author Leung
 * @date  2020/7/23 21:25
 */
class LoginActivity : AppCompatActivity() {

    /**
     * 验证手机号码是否正确
     */
    private var isPhoneNumber: Boolean = false

    /**
     * 计时器
     */
    private val timer = object : CountDownTimer(60 * 1000, 1000) {
        override fun onFinish() {
            btn_login_send.text = "重发"
            btn_login_send.isEnabled = true
            this.cancel()
        }

        override fun onTick(millisUntilFinished: Long) {
            btn_login_send.isEnabled = false
            val second = millisUntilFinished / 1000
            btn_login_send.text = String.format("%d秒", second)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        // 验证手机号码
        et_login_Phone.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (s.toString().isEmpty()) {
                    tv_login_hint.visibility = View.GONE
                    return
                }
                if (!SimpleUtil.isPhoneNumber(s.toString())) {
                    tv_login_hint.visibility = View.VISIBLE
                    isPhoneNumber = false
                } else {
                    tv_login_hint.visibility = View.GONE
                    isPhoneNumber = true
                    btn_login_send.isEnabled = true
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

        })

        // 发送验证码
        btn_login_send.setOnClickListener {
            if (isPhoneNumber) {
                BmobSMS.requestSMSCode(et_login_Phone.text.toString(), "吾掌勺", object : QueryListener<Int>() {
                    override fun done(smsId: Int?, e: BmobException?) {
                        if (e == null) {
                            ToastUtil.showToast(this@LoginActivity, "发送验证码成功，短信ID：$smsId")
                            timer.start()
                        } else {
                            ToastUtil.showToast(this@LoginActivity, "发送验证码失败，${e.message}")
                        }
                    }
                })
            }
        }

        // 登录
        btn_login_login.setOnClickListener {
            if (et_login_Phone.text.isNotEmpty() && et_login_verify.text.isNotEmpty() && isPhoneNumber && cb_login_agree.isChecked) {
                BmobSMS.verifySmsCode(
                        et_login_Phone.text.toString(),     // 手机号码
                        et_login_verify.text.toString(),    // 验证码
                        object : UpdateListener() {
                            override fun done(p0: BmobException?) {
                                if (p0 == null) {
                                    startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                                    finish()
                                    SharedPreUtil.saveBoolean(this@LoginActivity, "isLogin", true)
                                } else {
                                    tv_login_verify_hint.visibility = View.VISIBLE
                                }
                            }

                        })
            }
        }

        // 用户协议
        tv_login_agreement.setOnClickListener {
            startActivity(Intent(this, AgreementActivity::class.java))
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        // 监听View的焦点
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view is EditText) {
                SimpleUtil.hideInputMethod(view)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

}
